﻿using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.IO;

namespace Isuka.Excel
{
    public class XWorkbooks
        : ExcelObject
        , IEnumerable<XWorkbook>
    {
        internal XWorkbooks(XApplication application, object workbooks)
            : base(application, workbooks)
        {
            Contract.Requires(application != null);
            Contract.Requires(workbooks != null);
        }

        public XWorkbook this[int index]
        {
            get
            {
                return new XWorkbook(Application, Object[index]);
            }
        }

        public XWorkbook this[string key]
        {
            get
            {
                return new XWorkbook(Application, Object[key]);
            }
        }

        public int Count
        {
            get { return Object.Count; }
        }

        /// <summary>
        /// 新しいワークブックを作成します。
        /// </summary>
        /// <returns></returns>
        public XWorkbook CreateNew()
        {
            Contract.Ensures(Contract.Result<XWorkbook>() != null);

            object book = Object.Add();
            Contract.Assume(book != null);
            return new XWorkbook(Application, book);
        }

        /// <summary>
        /// ワークブックを開きます
        /// </summary>
        /// <param name="filepath"></param>
        /// <returns></returns>
        public XWorkbook Open(string filepath)
        {
            Contract.Requires<ArgumentNullException>(filepath != null, "filepath");
            Contract.Ensures(Contract.Result<XWorkbook>() != null);

            if (!File.Exists(filepath))
            {
                throw new FileNotFoundException(Messages.Error.E_FILE_NOT_FOUND, filepath);
            }
            object book = Object.Open(filepath);
            Contract.Assume(book != null);
            return new XWorkbook(Application, book);
        }

        #region IEnumerable<XWorkbook> メンバー

        public IEnumerator<XWorkbook> GetEnumerator()
        {
            foreach (var book in Object)
            {
                yield return new XWorkbook(Application, book);
            }
        }

        #endregion

        #region IEnumerable メンバー

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        #endregion
    }
}
